package kk.yy.myaccount.main.service;

import android.telecom.Call;
import android.util.Log;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import kk.yy.myaccount.main.model.AccountItem;
import kk.yy.myaccount.utils.ContentUtils;

import kk.yy.myaccount.utils.MessageData;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class AccountService {
    public void selectData()
    {
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .build();
        Request request = new Request.Builder()
                .url(ContentUtils.ACCOUNT_SELECT)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {

            @Override
            public void onFailure(okhttp3.Call call, IOException e) {

            }

            @Override
            public void onResponse(okhttp3.Call call, Response response) throws IOException {
                parseAllShopping(response);
            }
        });

    }

    private void parseAllShopping(Response response) throws IOException {
        //获取json数据
        String responseData=response.body().string();
        Log.d("xgk_debug",responseData);
        try{
            JSONArray jsonArray=new JSONArray(responseData);
            List data=new ArrayList<>();
            for(int i=0;i<jsonArray.length();i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String result = jsonObject.getString("check");
                if (result.equals("1")) {
                    String aid=jsonObject.getString("aid");
                    String acontent=jsonObject.getString("acontent");
                    String atime=jsonObject.getString("atime");
                    String aprice=jsonObject.getString("aprice");
                    String atype=jsonObject.getString("atype");
                    AccountItem accountItem;
                    if(atype.equals("支出")) {
                    accountItem =new AccountItem(AccountItem.OUT);
                    }else {
                        accountItem =new AccountItem(AccountItem.INPUT);
                    }
                    accountItem.setAccountContent(acontent);
                    accountItem.setAccountTime(atime);
                    accountItem.setPrice(Double.parseDouble(aprice));
                    data.add(accountItem);
                }
            }
            EventBus.getDefault().post(new MessageData("select",data));

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
